﻿using ICSharpCode.SharpZipLib.GZip;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Services.ServiceInterface
{
    /// <summary>
    /// 
    /// </summary>
    public class HttpResponseMessageWrapper : IHttpResponseMessage
    {
        private readonly HttpWebResponse httpWebResponseMessage;

        public HttpResponseMessageWrapper(HttpWebResponse httpResponseMessage)
        {
            httpWebResponseMessage = httpResponseMessage;
        }

        public Task<string> ReadAsStringAsync()
        {
            return Task.Run(() => ReadAsString());
        }

        private string ReadAsString()
        {
            if (httpWebResponseMessage == null)
                return string.Empty;
            string header = httpWebResponseMessage.Headers["Content-Encoding"];
            Stream stream = httpWebResponseMessage.GetResponseStream();

            if (!string.IsNullOrEmpty(header) && header.ToLower().Contains("gzip"))
            {
                Stream streamgzip = new GZipInputStream(httpWebResponseMessage.GetResponseStream());
                XDocument document = XDocument.Load(streamgzip);
                String returnString = document.ToString();
                return returnString;
            }
            else
            {
                using (var resder = new StreamReader(stream))
                {
                    return resder.ReadToEnd();
                }
            }
        }

        public Task<byte[]> ReadAsByteArrayAsync()
        {
            return null;
        }

        public Task<Stream> ReadAsStreamAsync()
        {
            return null;
        }

        public string[] GetCookies()
        {
            if (httpWebResponseMessage == null)
                return null;
            string cookCollect = httpWebResponseMessage.Headers["Set-Cookie"];

            if (string.IsNullOrEmpty(cookCollect))
                return null;

            string[] parts = cookCollect.Split(new string[] { ",  " }, StringSplitOptions.RemoveEmptyEntries);

            return parts;
        }
    }
}
